<?php

namespace app\controller;

use mysqli;
use think\facade\Db;
use think\facade\Env;
use Exception;

class Index
{

    public function index()
    {
        return '<style>*{ padding: 0; margin: 0; }</style><iframe src="https://www.thinkphp.cn/welcome?version=' . \think\facade\App::version() . '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>';
    }

    public function hello($name = 'ThinkPHP8')
    {
        return 'hello,' . $name;
    }

    //获取配置的参数从.env文件和config目录
    public function config(string $name = '')
    {
        // return Env::get('DB_USER');
        // echo Env::has("DB_USER"); Env如果存在"DB_USER"返回1 
        // return config("app.default_app");
        return config("database.connections.mysql.hostname");
    }

    //URL访问模式——单应用模式：http://tp8.com/Index/Index（类）/test（方法）/参数名/参数的值
    // 例如：http://tp8.com:8000/index/test/test/sdfsdfsd
    public function test($test = '')
    {
        return '' . $test . '';
    }
    // 通过设备ID获取设备信息
    //get方式:http://tp8.com:8000/Index/devices/deviceID/5
    public function devices($deviceID = 0)
    {
        $sql = "SELECT * FROM devices where devices.id =" . $deviceID;
        // echo $sql;
        //返回数组
        $result = Db::query($sql);
        header('Content-Type:application/json; charset=utf-8');
        return exit(json_encode($result));
    }

    //get方式:http://tp8.com:8000/Index/login/deviceID/1/userName/aaaaa
    public function login($deviceID = 0, $userName = "")
    {
        // echo $deviceID
        $sql1 = "select * from employees where name = " . "'" . $userName . "'";
        $sql2 = "select * from devices where id = " . $deviceID;
        // echo $sql;
        $result1 = Db::query($sql1);
        $result2 = Db::query($sql2);
        if (count($result1) > 0 && count($result2) > 0) {
            $pointCheckList['result'] = true;
        } else {
            $pointCheckList['result'] = false;
        }
        header('Content-Type:application/json; charset=utf-8');
        return exit(json_encode($pointCheckList));
    }

    //获取运行检查项目（current check project)
    // get方式：http://tp8.com:8000/Index/ccp?deviceID=1
    // 也可以：http://tp8.com:8000/Index/ccp/deviceID/1

    public function ccp($deviceID = 0)
    {

        // echo $deviceID;
        $sql = "SELECT * from ccp WHERE ccp.device_name = (select devices.name from devices where devices.id = $deviceID)";
        // echo $sql;
        $result = Db::query($sql);
        header('Content-Type:application/json; charset=utf-8');
        return exit(json_encode($result[0]));
    }

    // 获取班次时段规定信息
    // http://tp8.com:8000/Index/working
    public function working()
    {
        // echo $deviceID;
        $sql = "SELECT * FROM working";
        // echo $sql;
        $result = Db::query($sql);

        header('Content-Type:application/json; charset=utf-8');
        return exit(json_encode($result));
    }

    //获取指定设备的运行日志
    //http://tp8.com:8000/Index/currentLogStory/deviceID/2

    public function currentLogStory($deviceID = 0)
    {
        // echo $deviceID;
        $sql = "SELECT 
        ct.start, ct.end, ct.total, ct.current, ct.voltage, 
        ct.depth_flag, ct.telephone, ct.bell, ct.video, ct.brake_driving,
        ct.brake_pressure, ct.motor, ct.gearbox, ct.engine_oil, ct.pressure_oil,
        ct.lubricant, e.name as ename, d.name as dname, ct.submit_date, w.name as wname, ct.date
        FROM `ct` 
        JOIN employees as e on e.id = ct.e_id
        JOIN devices as d on d.id = ct.d_id
        JOIN working as w on w.id = ct.w_id where ct.d_id = $deviceID order by ct.date desc";
        // echo $sql;
        $result = Db::query($sql);

        header('Content-Type:application/json; charset=utf-8');
        return exit(json_encode($result));
    }

    //获取指定设备的点检项目
    //http://tp8.com:8000/Index/pointCheckList/deviceID/2

    public function pointCheckList($deviceID)
    {
        //这种方式需要：http://tp8.com:8000/Index/pointCheckList?deviceID=2
        // $deviceID = $_GET['deviceID'];

        // echo $deviceID;
        $sql = "SELECT p.id,p.project,p.standart,p.method,d.location,d.name FROM pointtable as p, devices as d WHERE p.device_name = d.name and d.id = " . $deviceID;
        // echo $sql;
        $result = Db::query($sql);
        header('Content-Type:application/json; charset=utf-8');
        return exit(json_encode($result));
    }

    //获取某一天的某班的点检结果
    // http://tp8.com:8000/Index/pointCheckDetail?deviceID=1&workingID=1&date=2024-12-04%

    public function pointCheckDetail()
    {

        $deviceID = $_GET['deviceID'];
        $workingID = $_GET['workingID'];
        $date = $_GET['date'] . "%";
        // echo $deviceID;
        $sql = "SELECT p.id,p.project,p.standart,p.method,c.result_id,c.modify_info
FROM checking as c 
JOIN devices as d on d.id = c.device_id
JOIN employees as e on e.id = c.employee_id
JOIN pointtable as p on p.id = c.pointtable_id
JOIN result as r on r.id = c.result_id
JOIN working as w on w.id = c.working_id
WHERE c.date like " . "'" . $date . "'" . " and c.working_id = " . $workingID . " and c.device_id = " . $deviceID . " order by p.id asc";
        // echo $sql;

        $result = Db::query($sql);

        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($result));
    }

    // http://tp8.com:8000/Index/pointCheckStory?deviceID=1
    //获取点检历史
    public function pointCheckStory()
    {


        $deviceID = $_GET['deviceID'];
        // echo $deviceID;
        $sql = "SELECT 
a.result_count as normal_count, 
b.result_count as warm_count,
a.date,
a.time,
a.working_name,
a.working_id,
a.employee
FROM (SELECT count(c.pointtable_id) as result_count,r.name as result, c.date,c.time, w.`name` as working_name,w.id as working_id , e.`name` as employee FROM checking as c 
JOIN working as w on  c.working_id = w.id
JOIN employees as e on e.id = c.employee_id
JOIN result as r on c.result_id = r.id
WHERE c.device_id = $deviceID and r.id = 1  GROUP BY c.date,c.time, c.working_id,c.employee_id,c.result_id) as a 
left JOIN (SELECT count(c.pointtable_id) as result_count,r.name as result, c.date,c.time, w.`name` as working_name,w.id as working_id , e.`name` as employee FROM checking as c 
JOIN working as w on  c.working_id = w.id
JOIN employees as e on e.id = c.employee_id
JOIN result as r on c.result_id = r.id
WHERE c.device_id = $deviceID and r.id = 2  GROUP BY c.date,c.time, c.working_id,c.employee_id,c.result_id) as b
on a.date = b.date 
ORDER BY a.date DESC";
        // echo $sql;
        $result = Db::query($sql);

        header('Content-Type:application/json; charset=utf-8');
        exit(json_encode($result));
    }

    //保存运行记录表的数据
    //http://tp8.com:8000/Index/saveCT
    public function saveCT()
    {

        //客户端数据结构
        // {
        //     d:{
        // 0: {key: "2024-12-1 11:11"}
        // 1: {key: "2024-12-1 11:11"}
        // 2: {key: "total"}
        // 3: {key: "current"}
        // 4: {key: "voltage"}
        // 5: {key: "depth_flag"}
        // 6: {key: "telephone"}
        // 7: {key: "bell"}
        // 8: {key: "video"}
        // 9: {key: "brake_driving"}
        // 10: {key: "brake_pressure"}
        // 11: {key: "motor"}
        // 12: {key: "gearbox"}
        // 13: {key: "engine_oil"}
        // 14: {key: "pressure_oil"}
        // 15: {key: "lubricant"}                 
        // 16: {key: "2024-12-21 16:54:00"}
        // 17: {key: "2024-12-21"}
        // 18: {key: "aaaaa"}
        // 19: {key: "1"}
        //     }
        // }
        try {
            $d = file_get_contents('php://input');
            $data = json_decode($d, true)['d'];
            // echo $data[0]['key'];

            //获取用户ID
            $eID = 0;
            $userName = $data[18]['key'];
            $result1 = Db::query("SELECT * FROM employees WHERE employees.name = " . "'" . $userName . "'");
            $eID = $result1[0]['id'];
            header('Content-Type:application/json; charset=utf-8');
            $result = array();

            $sql = "INSERT INTO `devicepointchecksubmit`.`ct`(`start`, `end`, `total`, `current`, `voltage`, `depth_flag`, `telephone`, `bell`, `video`, `brake_driving`, `brake_pressure`, `motor`, `gearbox`, `engine_oil`, `pressure_oil`, `lubricant`, `e_id`, `d_id`, `submit_date`, `w_id`, `date`)
                VALUES ("
                . "'" . $data[0]["key"] . "'" . ","
                . "'" . $data[1]["key"] . "'" . ","
                . "'" . $data[2]["key"] . "'" . ","
                . "'" . $data[3]["key"] . "'" . ","
                . "'" . $data[4]["key"] . "'" . ","
                . "'" . $data[5]["key"] . "'" . ","
                . "'" . $data[6]["key"] . "'" . ","
                . "'" . $data[7]["key"] . "'" . ","
                . "'" . $data[8]["key"] . "'" . ","
                . "'" . $data[9]["key"] . "'" . ","
                . "'" . $data[10]["key"] . "'" . ","
                . "'" . $data[11]["key"] . "'" . ","
                . "'" . $data[12]["key"] . "'" . ","
                . "'" . $data[13]["key"] . "'" . ","
                . "'" . $data[14]["key"] . "'" . ","
                . "'" . $data[15]["key"] . "'" . ","
                . $eID . ","
                . $data[19]["key"] . ","
                . "'" . $data[16]["key"] . "'" . ","
                . $data[20]["key"] . ","
                . "'" . $data[17]["key"] . "'" . ")";

            // echo $sql;
            // execute用于更新和写入数据的sql操作，如果数据非法或者查询错误则返回false ，否则返回影响的记录数。
            if (Db::execute($sql) == false) {
                $result['result'] = false;
                $result['info'] = "保存失败！";
            } else {
                $result['result'] = true;
                $result['info'] = "保存成功！";
            }
        } catch (Exception $e) {
            $result["result"] = false;
            $result["info"] = $e->getMessage();
        }
        // // echo "数据".$d;
        // echo $sql;
        // $result['result'] = false;
        return  exit(json_encode($result));
    }
    //http://tp8.com:8000/Index/savePCT
    public function savePCT()
    {

        try {
            // $d = $_GET['index'];
            $d = file_get_contents('php://input');
            // echo $d;

            $a = json_decode($d, true)['d'];
            // echo $a[0]['deviceID'];//1

            //获取用户ID
            $eID = 0;
            $userName = $a[0]['employeeId'];
            $result1 = Db::query("SELECT * FROM employees WHERE employees.name = " . "'" . $userName . "'");
            $eID = $result1[0]['id'];
            header('Content-Type:application/json; charset=utf-8');
            $result = array();
            for ($i = 0; $i < count($a); $i++) {
                $deviceID = $a[$i]['deviceID'];
                // $employeeId =$a[$i]['employeeId'];
                $pointtableId = $a[$i]['pointtableId'];
                $date = $a[$i]['date'];
                $modifyInfo = $a[$i]['modifyInfo'];
                $workingId = $a[$i]['workingId'];
                $resultId = $a[$i]['resultId'];
                $time = $a[$i]['time'];
                $sql = "INSERT INTO checking(device_id, employee_id, pointtable_id, date,modify_info,working_id,result_id,time)
 VALUES (" . $deviceID . "," . $eID . "," . $pointtableId . "," . "'" . $date . "'" . "," . "'" . $modifyInfo . "'" . "," . $workingId . "," . $resultId . "," . "'" . $time . "'" . ")";
                if (Db::execute($sql) === false) {
                    $result['result'] = false;
                    $result['info'] = "保存失败!";
                    break;
                } else {
                    $result['result'] = true;
                    $result['info'] = "保存成功!";

                }
            }
        } catch (Exception $e) {
            $result['result'] = false;
            $result['info'] = $e->getMessage();
        }
        // // echo "数据".$d;
        // echo $sql;
        // $result['result'] = false;
        return exit(json_encode($result));
    }
}
